<?php
Yii::import('application.extensions.artichow.*');
Yii::import('application.vendors.*');
//

class ProjectController extends CController {

	const PAGE_SIZE = 10;

	public function filters() {
		return array (
			'ShowProject + show',
			'EditProject + edit',
			'accessControl' // perform access control for CRUD operations
		);
	}

	public function actions() {
		return array (
			'create' => 'adviser.controllers.project.CreateProjectFormAction',
			'edit' => 'adviser.controllers.project.EditProjectFormAction',
			'steps' => 'adviser.controllers.project.StepsAction',
		// 'edit' => 'adviser.controllers.meeting.EditAction'
		);
	}
	
	public function filterShowProject($filterChain)
	{
		$project = Project::model()->findByPk($_GET['id']);
		if (!ProjectHelper::canReadProject($project))
		{
			throw new CHttpException(403,'Access Denied');
		}
		$filterChain->run();
	}

	public function filterEditProject($filterChain)
	{
		$project = Project::model()->findByPk($_GET['id']);
		if (!ProjectHelper::canEditProject($project))
		{
			throw new CHttpException(403,'Access Denied');
		}
		$filterChain->run();
	}

	public function accessRules() {
		return array (
		array (
				'allow', // allow all users to perform 'list' and 'show' actions
				'actions' => array ('findCity', 'stepJs', 'drawGraph'), 
				'users' => array('*')
		),
		array (
				'allow', // allow all users to perform 'list' and 'show' actions
				'actions' => array ('search', 'create', 'edit', 'steps', 'show', 'edit', 'saveInBackground'), 
				'roles' => array('Adviser.canCreateProject')
		),
		array (
				'allow', // allow all users to perform 'list' and 'show' actions
				'actions' => array ('search', 'show', 'drawGraph'), 
				'roles' => array('Adviser.canAccessAllProjects')
		),
		array (
				'deny', // deny all users
				'users' => array ('*')
		)
		);
	}

	public function actionIndex() {
		$this->redirect(array('search'));
	}

	public function actionSearch() {
		$model = new SearchForm();

		$sort = new SearchSort('SearchItem');

		$results = null;
		$pages = null;
		
		$search = false;
		if (isset($_GET['ts']) && isset($_SESSION[$_GET['ts']])) {
			$model->attributes = Yii::app()->session->get($_GET['ts']);
			$search = true;
		}
		
		if (isset ($_POST['SearchForm'])) {
			$model->attributes = $_POST['SearchForm'];
			Yii::app()->session->add($_GET['ts'], $model->attributes);
			$search = true;
		}

		if ($search) {
			$criteria = $model->buildCriteria();

			$pages = new CPagination(SearchItem::model()->count($criteria));
			$pages->pageSize = self::PAGE_SIZE;
			$pages->applyLimit($criteria);
			$sort->applyOrder($criteria);

			$results = SearchItem::model()->findAll($criteria);
		}

		if (!isset($_GET['ts'])) {
			$_GET['ts'] = 'SF_'.time();
		}
		
		$this->render('search', array (
			'model' => $model,
			'columns' => $model->getColumnsList(),
			'results' => $results,
			'sort' => $sort,
			'pages' => $pages,
		'ts' => $_GET['ts']
		));
	}

	public $project = null;

	public function actionShow() {
		$this->layout = 'project';

		$this->project = Project::model()->findByPk($_GET['id']);

		$this->render('show', array (
			'id' => $_GET['id'],
			'project' => $this->project
		));
	}

	public function actionDrawGraph() {
		require_once ('Artichow/LinePlot.class.php');

		if (!isset ($_GET['width']))
		$_GET['width'] = 800;
		if (!isset ($_GET['height']))
		$_GET['height'] = 400;
		$graph = new Graph($_GET['width'], $_GET['height']);
		$graph->setAntiAliasing(TRUE);
		$group = new HPlotGroup;
		
		$values = array (
			'xlabel' => array()
		);

		if (isset ($_GET['id'])) {
			$project_id = $_GET['id'];
			$attr = array (
				'project_id' => $project_id
			);
			$sql = '';
			$stats = TopicsStat::model()->findAllByAttributes($attr);
			if ($stats != null) {
				$value = array (
					'color' => new Color(200, 0, 0),
					'data' => array (),
					'legend' => 'Previsions'
					);
					if (is_array($stats)) {
						foreach ($stats as $stat) {
							$value['data'][$stat->end_date] = $stat->nb;
							$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
						}
					} else {
						$value['data'][$stats->end_date] = $stats->nb;
						$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
					}
					$values[] = $value;
			}

			if (isset ($GET['date'])) {
				$sql = "end_date <= '" . $GET['date'] . "'";
			}
			$stats = TopicsStatAdviser::model()->findAllByAttributes(array (
				'project_id' => $project_id
			), $sql);
			if ($stats != null) {
				$value = array (
					'color' => new Color(0, 200, 0),
					'data' => array (),
					'legend' => 'Validation conseiller'
					);
					if (is_array($stats)) {
						foreach ($stats as $stat) {
							$value['data'][$stat->end_date] = $stat->nb;
							$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
						}
					} else {
						$value['data'][$stats->end_date] = $stats->nb;
						$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
					}
					$values[] = $value;
			}

			$stats = TopicsStatOwner::model()->findAllByAttributes(array (
				'project_id' => $project_id
			), $sql);
			if ($stats != null) {
				$value = array (
					'color' => new Color(0, 0, 200),
					'data' => array (),
					'legend' => 'Validation porteur'
					);
					if (is_array($stats)) {
						foreach ($stats as $stat) {
							$value['data'][$stat->end_date] = $stat->nb;
							$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
						}
					} else {
						$value['data'][$stats->end_date] = $stats->nb;
						$values['xlabel'][$stat->end_date] = Constants::fromSqlDate($stat->end_date);
					}
					$values[] = $value;
			}

		}

		$group->initialize($values);
		$group->axis->bottom->label->setAngle(90);
	$group->axis->bottom->label->setAlign(NULL, Label::TOP);
	$group->axis->bottom->label->setPadding(15, 1, 0, 6);
		
		$graph->add($group);

		header("Content-type: image/png;");
		//readfile("C:\\dev\\php\\private_html\\bg\\report\\logo_121x200.jpg");
		$graph->draw(Graph::DRAW_DISPLAY);
	}

	public function actionDrawHistogram() {
		//		if (!isset ($_GET['width']))
		//			$_GET['width']= 800;
		//		if (!isset ($_GET['height']))
		//			$_GET['height']= 400;
		//		$graph= new Graph($_GET['width'], $_GET['height']);
		//		$graph->setAntiAliasing(TRUE);
		//		$group= new HPlotGroup;
		//
		//		$values= array ();
		//
		//		if (isset ($_GET['id'])) {
		//			$project_id= $_GET['id'];
		//			$attr = array (
		//				'project_id' => $project_id
		//			);
		//
		//			$command =
		//
		//		}
		//
		//		$group->initialize($values);
		//		$graph->add($group);
		//
		//		header("Content-type: image/png");
		//		$graph->draw(Graph::DRAW_DISPLAY);
	}

	public function actionSaveInBackground() {
		if (Yii::app()->request->isAjaxRequest) {
			Yii::app()->session->open();
			Yii::log(CVarDumper::dumpAsString($_POST, 3, false), CLogger::LEVEL_TRACE, "SaveInBackground");
			Yii::log("NOT IMPLEMENTED", CLogger::LEVEL_ERROR, "SaveInBackground");
		}
	}
	
	public function actionFindCity() {
		if (Yii::app()->request->isAjaxRequest && isset ($_GET['q'])) {
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['q'];
		
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = min($_GET['limit'], 50);
			$cities = $this->findCities($name, $limit);
			$returnVal = '';
			foreach ($cities as $city) {
				$returnVal .= $city->label . '|' .	$city->id . "\n";
			}
			echo $returnVal;
		}
	}

	public function findCities($name, $limit) {
		$name = strtoupper($name);
		$name = str_replace("SAINTE ", "STE ", $name);
		$name = str_replace("SAINT ", "ST ", $name);
		$name = str_replace("  ", " ", $name);
	
		$criteria = new CDbCriteria;
		$criteria->condition = "city_name LIKE :sterm or postal_code like :sterm order by city_name ";
		$criteria->params = array (
			":sterm" => "$name%"
		);
		$criteria->limit = $limit;
		return City::model()->findAll($criteria);
	}

	public function dashed($text) {
		if (is_array($text)) {
			$s = "<span>";
			foreach($text as $t){
				$s .= $this->dashed($t."&nbsp;");
			}
			$s .= "</span>";
			return $s;
		} else {
			return "<div style='border-bottom: 1px lightgray dashed;'>$text</div>";
		}
	}

	public function printHiddenField($model)
	{
		$arr = $model->getHiddenFields();
		foreach ($arr as $field) {
			if (is_array($model->$field))
			{
				foreach ($model->$field as $id=>$specificDatum) {
					$name = $field.'['.$id.']';
					$name = CHtml::resolveName($model,$name);
					echo CHtml::tag('input',array('size'=>60,'maxlength'=>255, 'type' => 'hidden', 'name'=>$name, 'value'=>$specificDatum, 'id' => $name));
				}
			}else{
				echo CHtml::activeHiddenField($model, $field);
			}
		}
	}
}

class SearchSort extends CSort {
	protected function createLink($attribute, $label, $url, $htmlOptions) {
		$htmlOptions['onclick'] = "submit('$url');";
		return CHtml::link($label, "#", $htmlOptions);
	}
}
?>